const sqlite3 = require('../app/backend/node_modules/sqlite3').verbose();
const db = new sqlite3.Database('../app/backend/data/pph.sqlite');

console.log('🧪 测试前端节拍显示逻辑...');
console.log('=====================================');

async function testFrontendTaktDisplay() {
  return new Promise((resolve, reject) => {
    // 模拟前端显示逻辑测试
    console.log('📊 获取测试数据...');
    db.all(`SELECT record_date, line_name, is_whole_machine, 
                   target_takt_time, target_motor_takt_time,
                   material_code, product_name
            FROM pph_records 
            WHERE material_code = 'A0101150004' 
            AND record_date >= '2025-09-18'
            ORDER BY record_date DESC, line_name LIMIT 8`, (err, rows) => {
      if (err) {
        console.error('❌ 查询失败:', err);
        return reject(err);
      }
      
      console.log('📋 测试数据:');
      console.table(rows);
      
      console.log('\n🖥️ 前端显示效果模拟:');
      console.log('=====================================');
      
      // 模拟前端表格显示
      console.log('记录日期    | 生产线 | 生产类型 | 整机节拍 | 电机节拍');
      console.log('-----------|-------|---------|---------|----------');
      
      rows.forEach(row => {
        const productionType = row.is_whole_machine === 1 ? '整机' : '电机';
        
        // 模拟前端智能显示逻辑
        const wholeTaktDisplay = row.is_whole_machine === 1 
          ? (row.target_takt_time || '-') 
          : '-';
          
        const motorTaktDisplay = row.is_whole_machine === 0 
          ? (row.target_motor_takt_time || '-') 
          : '-';
        
        console.log(`${row.record_date} | ${row.line_name.padStart(5)} | ${productionType.padStart(6)} | ${String(wholeTaktDisplay).padStart(7)} | ${String(motorTaktDisplay).padStart(7)}`);
      });
      
      console.log('\n📈 显示逻辑验证:');
      
      let correctCount = 0;
      let totalCount = rows.length;
      
      rows.forEach((row, index) => {
        const isWhole = row.is_whole_machine === 1;
        const wholeTaktDisplay = isWhole ? (row.target_takt_time || '-') : '-';
        const motorTaktDisplay = !isWhole ? (row.target_motor_takt_time || '-') : '-';
        
        const hasCorrectDisplay = isWhole 
          ? (wholeTaktDisplay !== '-' && motorTaktDisplay === '-')
          : (wholeTaktDisplay === '-' && motorTaktDisplay !== '-');
        
        if (hasCorrectDisplay) correctCount++;
        
        console.log(`记录${index + 1}: ${row.line_name}号线 ${isWhole ? '整机' : '电机'}生产`);
        console.log(`  - 整机节拍列显示: ${wholeTaktDisplay}`);
        console.log(`  - 电机节拍列显示: ${motorTaktDisplay}`);
        console.log(`  - 显示逻辑: ${hasCorrectDisplay ? '✅ 正确' : '❌ 错误'}`);
      });
      
      console.log('\n📊 测试结果统计:');
      console.log(`- 总记录数: ${totalCount}`);
      console.log(`- 显示正确: ${correctCount}`);
      console.log(`- 显示错误: ${totalCount - correctCount}`);
      console.log(`- 正确率: ${totalCount > 0 ? ((correctCount / totalCount) * 100).toFixed(1) : 0}%`);
      
      if (correctCount === totalCount) {
        console.log('\n✅ 前端显示逻辑测试通过！');
      } else {
        console.log('\n❌ 前端显示逻辑存在问题，需要检查数据或代码');
      }
      
      // 检查数据完整性
      console.log('\n🔍 数据完整性检查:');
      
      const wholeRecords = rows.filter(r => r.is_whole_machine === 1);
      const motorRecords = rows.filter(r => r.is_whole_machine === 0);
      
      const wholeWithTakt = wholeRecords.filter(r => r.target_takt_time !== null);
      const motorWithTakt = motorRecords.filter(r => r.target_motor_takt_time !== null);
      
      console.log(`- 整机生产记录: ${wholeRecords.length} 条，有节拍数据: ${wholeWithTakt.length} 条`);
      console.log(`- 电机生产记录: ${motorRecords.length} 条，有节拍数据: ${motorWithTakt.length} 条`);
      
      if (wholeRecords.length > 0 && wholeWithTakt.length === 0) {
        console.log('⚠️ 整机生产记录缺少节拍数据');
      }
      
      if (motorRecords.length > 0 && motorWithTakt.length === 0) {
        console.log('⚠️ 电机生产记录缺少节拍数据');
      }
      
      db.close();
      resolve({
        totalCount,
        correctCount,
        successRate: totalCount > 0 ? (correctCount / totalCount) * 100 : 0,
        wholeRecords: wholeRecords.length,
        motorRecords: motorRecords.length,
        wholeWithTakt: wholeWithTakt.length,
        motorWithTakt: motorWithTakt.length
      });
    });
  });
}

// 执行测试
testFrontendTaktDisplay().then(result => {
  console.log('\n🎯 测试完成！');
  if (result.successRate === 100) {
    console.log('✅ 前端修改可以部署到服务器');
  } else {
    console.log('❌ 需要先修复数据问题再部署前端');
  }
}).catch(err => {
  console.error('❌ 测试失败:', err);
  process.exit(1);
});
